from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeSerializer(serializers.Serializer):
    image_code_id = serializers.UUIDField(write_only=True)
    text = serializers.CharField(max_length=4, min_length=4, write_only=True)

    def validate(self, attrs):
        image_code_id = attrs.get('image_code_id')
        text = attrs.get('text')
        redis_con = get_redis_connection('verify')
        real_image_code = redis_con.get('image_code_%s'%image_code_id)
        redis_con.delete('image_code_%s' % image_code_id)
        if not real_image_code:
            raise serializers.ValidationError('无效图片验证码')
        if real_image_code.decode().lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        mobile = self.context['view'].kwargs['mobile']
        real_image_code = redis_con.get('send_flag_%s' % mobile)
        if real_image_code:
            raise serializers.ValidationError('请求频繁')

        return attrs